<template>
    <el-container class="comment-container">
        <!-- 评论输入区域 -->
        <el-header style="display: flex;flex-direction: column;align-self: start;width: 100%;height: auto;">
            <h2>评论</h2>
            <div v-if="isLoggedIn" style="display: flex;justify-content:flex-start;align-items: center;">
                <el-avatar shape="square" :size="60" :src="userAvatar || defalutAvatar" />
                <el-input v-model="commentContent" style="width: 540px;padding-left: 2%;" :rows="2" type="textarea"
                    placeholder="写下你的评论..." />
            </div>
            <div v-else style="text-align: center;">
                <el-button type="primary" @click="handleLogin">登录后发表评论</el-button>
            </div>
            <div v-if="isLoggedIn" style="display: flex;justify-content: flex-end;margin-top: 10px;">
                <el-button type="primary" @click="submitComment" :loading="submitting">发表评论</el-button>
            </div>
        </el-header>

        <!-- 评论列表区域 -->
        <el-main>
            <div v-loading="loading">
                <div v-for="comment in comments" :key="comment.commentId">
                    <CommentItemComponent :comment="comment" @delete-comment="handleDeleteComment"
                        @submit-reply="handleSubmitReply" @like-comment="handleLikeComment"
                        @like-reply="handleLikeReply" @delete-reply="handleDeleteReply" />
                </div>
                <el-empty v-if="comments.length === 0" description="暂无评论" />
                <div style="margin-top: 20px; display: flex; justify-content: center;">
                    <el-pagination background layout="prev, pager, next" v-model:current-page="currentPage"
                        :page-count="pageCount" :pager-count=pagerCount />
                </div>
            </div>
        </el-main>
    </el-container>
</template>

<script lang="ts" setup>
import { defalutAvatar } from '@/utils/mediaUtils';
import { ref, onMounted, computed, watch } from 'vue';
import type { CommentAddDto, CommentDisplayDto, CommentQueryDto, CommentReplyDTO } from '@/types/commentType';
import CommentItemComponent from './CommentItemComponent.vue';
import { getValidToken, tokenAxios } from '@/utils/tokenAxiosUtils';
import { getUserInfo } from '@/utils/persistUtils';
import router from '@/router';
import { PageResultDto } from '@/types/commonType';

const props = defineProps({
    blogId: {
        type: Number,
        required: true
    }
});

const userInfo = getUserInfo();
const commentContent = ref('');
const comments = ref<CommentDisplayDto[]>([]);
const loading = ref(false);
const submitting = ref(false);

const currentPage = ref(1);
const pageCount = ref(1);
/**设置最大页码按钮数。 页码按钮的数量，当总页数超过该值时会折叠 */
const pagerCount = ref(11);

const isLoggedIn = computed(async () => await getValidToken() != null);
const userAvatar = computed(() => userInfo.avatar);

// 获取评论列表
const fetchComments = async () => {
    loading.value = true;
    var commentQueryDto = { blogId: props.blogId, pageIndex: currentPage.value } as CommentQueryDto;
    try {
        const res = await tokenAxios.post('/blogComment/query', commentQueryDto);
        ({ content: comments.value, totalPages: pagerCount.value } = res.data as PageResultDto<CommentDisplayDto>);
    } catch (error) {
        console.error('获取评论失败:', error);
        ElMessage.error('获取评论失败');
    } finally {
        loading.value = false;
    }
};

// 提交评论
const submitComment = async () => {
    if (!commentContent.value.trim()) {
        ElMessage.warning('请输入评论内容');
        return;
    }
    submitting.value = true;
    var commentAddDto = { blogId: props.blogId, commentContent: commentContent.value } as CommentAddDto;
    try {
        const res = await tokenAxios.post('/blogComment/add', commentAddDto);
        console.log('提交评论成功:', res.data);
        commentContent.value = '';
        ElMessage.success('评论发表成功');
        currentPage.value = 1; // 重置到第一页
        await fetchComments();
    } catch (error) {
        console.error('提交评论失败:', error);
        ElMessage.error('评论发表失败');
    } finally {
        submitting.value = false;
    }
};

// 处理删除评论
const handleDeleteComment = async (commentId: number) => {
    try {
        const res = await tokenAxios.post(`/blogComment/delete/${commentId}`);
        ElMessage.success('评论删除成功');
        console.log("评论删除成功:", res.data)
        // 如果当前页只有一条数据，且不是第一页，则返回上一页
        if (comments.value.length === 1 && currentPage.value > 1) {
            currentPage.value--;
        }
        await fetchComments();
    } catch (error) {
        console.error('删除评论失败:', error);
        ElMessage.error('删除评论失败');
    }
};

// 处理评论点赞
const handleLikeComment = async (commentId: number, isLike: boolean) => {
    if (!isLoggedIn.value) {
        ElMessage.warning('请先登录');
        return;
    }
    try {
        if (!isLike) {
            const res = await tokenAxios.post('/commentLike/add', { commentId: commentId });
            console.log("点赞成功！", res.data);
        }
        else {
            const res = await tokenAxios.post(`/commentLike/delete/${commentId}`);
            console.log("取消点赞成功！", res.data);
        }

        await fetchComments();
    } catch (error) {
        console.error('点赞/取消点赞失败:', error);
        ElMessage.error('点赞/取消点赞失败');
    }
};

// 处理提交回复
const handleSubmitReply = async (commentId: number, content: string, replyId?: number) => {
    if (!isLoggedIn.value) {
        ElMessage.warning('请先登录');
        return;
    }
    try {
        var commentReplyDTO = { commentId: commentId, parentReplyId: replyId, content: content } as CommentReplyDTO;
        const res = await tokenAxios.post('/commentReply/add', commentReplyDTO);
        console.log('回复发表成功', res.data)
        ElMessage.success('回复发表成功');
        // 保持在当前页，重新获取数据
        await fetchComments();
    } catch (error) {
        console.error('提交回复失败:', error);
        ElMessage.error('回复发表失败');
    }
};

const handleLikeReply = async (replyId: number, isLike: boolean) => {
    if (!isLoggedIn.value) {
        ElMessage.warning('请先登录');
        return;
    }

    try {
        if (!isLike) {
            const res = await tokenAxios.post(`/commentReplyLike/like/${replyId}`);
            console.log('点赞成功:', res.data)
            ElMessage.success('点赞成功');
        }
        else {
            const res = await tokenAxios.post(`/commentReplyLike/unlike/${replyId}`);
            console.log('取消点赞成功:', res.data)
            ElMessage.success('取消点赞成功');
        }

        // 保持在当前页，重新获取数据
        await fetchComments();
    } catch (error) {
        console.error('点赞/取消点赞失败:', error);
        ElMessage.error('点赞/取消点赞失败');
    }
}

const handleDeleteReply = async (replyId: number) => {
    if (!isLoggedIn.value) {
        ElMessage.warning('请先登录');
        return;
    }

    try {
        const res = await tokenAxios.post(`/commentReply/delete/${replyId}`);
        console.log('删除回复成功:', res.data)
        ElMessage.success('删除回复成功');

        // 保持在当前页，重新获取数据
        await fetchComments();
    } catch (error) {
        console.error('删除回复失败:', error);
        ElMessage.error('删除回复失败');
    }
}

// 处理登录
const handleLogin = () => {
    router.push('/login');
};

onMounted(() => {
    fetchComments();
});

watch(() => currentPage.value, (newPage) => {
    console.log('页码变化:', newPage)
    fetchComments();
})
</script>

<style scoped>
.comment-container {
    width: 600px;
    height: auto;
    background-color: #fff;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
</style>